<template>
  <div>
    <div class="pageTitleWhole">
      <a-breadcrumb :routes="routes">
        <template slot="itemRender" slot-scope="{ route, routes, paths }">
          <span v-if="routes.indexOf(route) === routes.length - 1">{{ route.breadcrumbName }}</span>
          <router-link v-else :to="`${basePath}/${paths.join('/')}`">{{ route.breadcrumbName }}</router-link>
        </template>
      </a-breadcrumb>
    </div>
    <div id="content">
      <a-form-model
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <!-- 船舶信息 -->
        <a-card>
          <div class="card-title">船舶信息</div>
          <a-row>
            <a-col :span="12">
              <a-form-model-item label="船舶名称" prop="name">
                <a-input v-model="form.name" :max-length="limitNumber" />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="船舶识别号" prop="identifier">
                <a-input v-model="form.identifier" :max-length="limitNumber" />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12">
              <a-form-model-item label="IMO编号" prop="imo">
                <a-input v-model="form.imo" :max-length="limitNumber" />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="装载量（TEU）" prop="loadingCapacity">
                <a-input v-model="form.loadingCapacity" :max-length="limitNumber" />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12">
              <a-form-model-item label="船舶类型" prop="shipType">
                <a-input v-model="form.shipType" :max-length="limitNumber" />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="建成日期" prop="buildTime">
                <a-date-picker @change="dateChange0" style="width:100%" />
                <!-- <a-input v-model="form.buildTime" :max-length="limitNumber" /> -->
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12">
              <a-form-model-item label="船籍港" prop="portOfRegistry">
                <a-input v-model="form.portOfRegistry" :max-length="limitNumber" />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="船长（米）" prop="length">
                <a-input v-model="form.length" :max-length="limitNumber" />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12">
              <a-form-model-item label="船宽（米）" prop="width">
                <a-input v-model="form.width" :max-length="limitNumber" />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="船高（米）" prop="height">
                <a-input v-model="form.height" :max-length="limitNumber" />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12">
              <a-form-model-item label="型深（米）" prop="depth">
                <a-input v-model="form.depth" :max-length="limitNumber" />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="总吨位（吨）" prop="tonnage">
                <a-input v-model="form.tonnage" :max-length="limitNumber" />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12">
              <a-form-model-item label="净吨位（吨）" prop="netTonnage">
                <a-input v-model="form.netTonnage" :max-length="limitNumber" />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="下次年检日期" prop="inspectionTime">
                <a-date-picker @change="dateChange1" style="width:100%" />
                <!-- <a-input v-model="form.inspectionTime" :max-length="limitNumber" /> -->
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12">
              <a-form-model-item label="下次保养日期" prop="maintenanceTime">
                <a-date-picker @change="dateChange2" style="width:100%" />
                <!-- <a-input v-model="form.maintenanceTime" :max-length="limitNumber" /> -->
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="保险到期日期" prop="insuranceExpireTime">
                <a-date-picker @change="dateChange3" style="width:100%" />
                <!-- <a-input v-model="form.insuranceExpireTime" :max-length="limitNumber" /> -->
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12">
              <a-form-model-item label="经营类型" prop="isSelfOperation">
                <a-select v-model="form.isSelfOperation">
                  <a-select-option value>请选择</a-select-option>
                  <a-select-option :value="1">自营</a-select-option>
                  <a-select-option :value="0">租赁</a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="船舶状态" prop="status">
                <a-select v-model="form.status">
                  <a-select-option value>请选择</a-select-option>
                  <a-select-option :value="1">正常</a-select-option>
                  <a-select-option :value="0">冻结</a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12">
              <a-form-model-item label="告警油量（吨）" prop="alarmOilQuantity">
                <!-- <a-input v-model="form.alarmOilQuantity" :max-length="limitNumber" /> -->
                <a-input-number
                  :min="0"
                  :max="999999999999"
                  :precision="0"
                  v-model="form.alarmOilQuantity"
                  style="width:100%"
                />
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-card>
        <!-- 船APP账号 -->
        <a-card>
          <div class="card-title">船APP账号</div>
          <a-row :gutter="[16]">
            <a-col :span="12">
              <a-form-model-item label="APP账号" prop="phone">
                <a-input v-model="form.shipInfoAccount.phone" :max-length="limitNumber" />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="密码" prop="password" style="margin-bottom: 0;">
                <a-input value="*********" disabled />
              </a-form-model-item>
              <a-col :offset="7">
                <span>初始密码为：jiahua123</span>
              </a-col>
            </a-col>
          </a-row>
          <a-row :gutter="[16]">
            <a-col :span="12">
              <a-form-model-item label="船长姓名" prop="captainName">
                <a-input v-model="form.shipInfoAccount.captainName" :max-length="limitNumber" />
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-card>
        <!-- 船东信息 -->
        <a-card v-show="form.isSelfOperation===0">
          <div class="card-title">船东信息</div>
          <a-row :gutter="[20]">
            <a-col :span="8">
              <a-form-model-item label="船东名称" style="margin-bottom:0">
                <a-auto-complete @select="onSelect" @search="onSearch">
                  <template slot="dataSource">
                    <a-select-option
                      v-for="(record,index) in shipOwner"
                      :key="index"
                      :value="record.name"
                    >{{ record.name }}</a-select-option>
                  </template>
                </a-auto-complete>
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <span>联系人：{{selectObj.linkMan}}</span>
            </a-col>
            <a-col :span="8">
              <span>联系电话：{{selectObj.linkManPhone}}</span>
            </a-col>
          </a-row>
          <a-row :gutter="[20]">
            <a-col :span="8">
              <span>统一信用代码/身份证：{{selectObj.identityCard}}</span>
            </a-col>
            <a-col :span="8">
              <span>地址：{{selectObj.address}}</span>
            </a-col>
            <a-col :span="8">
              <span>银行卡户名：{{selectObj.bankcardAccountName}}</span>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="8">
              <span>银行卡号：{{selectObj.bankcardAccountNumber}}</span>
            </a-col>
            <a-col :span="8">
              <span>银行卡开户行：{{selectObj.openingBank}}</span>
            </a-col>
          </a-row>
        </a-card>
        <a-card>
          <a-button type="primary" class="cardEdit" @click="uploadAgreement">
            <a-icon type="upload" />上传合同
          </a-button>
          <div class="card-title hasContent">船舶合同</div>
          <a-form-model-item prop="contractPics" :wrapperCol="{span:24}">
            <a-row>
              <a-col :span="22" :offset="1">
                <a-list>
                  <a-list-item v-for="(ag, index) in this.form.shipInfoContractList" :key="index">
                    <a-icon type="link" :style="{color: getColor(ag.beginTime, ag.endTime)}" />
                    合同有效期：{{ag.beginTime}} ~ {{ag.endTime}}
                    <a @click="checkAgreement(index)">查看</a>
                  </a-list-item>
                </a-list>
              </a-col>
            </a-row>
          </a-form-model-item>
        </a-card>
        <!-- 船舶营运证 -->
        <a-card class="busenPic">
          <div class="card-title">船舶营运证</div>
          <a-form-model-item prop="operationCertificatePics" :wrapperCol="{span:24}">
            <upload
              :uploadName="'operationCertificatePics'"
              :fatherList="[]"
              :length="10"
              @uploadFile="operationCertificatePics"
            ></upload>
          </a-form-model-item>
        </a-card>
        <!-- 保险保单 -->
        <a-card class="busenPic">
          <div class="card-title">保险保单</div>
          <a-form-model-item prop="insurancePolicyPics" :wrapperCol="{span:24}">
            <upload
              :uploadName="'insurancePolicyPics'"
              :fatherList="[]"
              :length="10"
              @uploadFile="insurancePolicyPics"
            ></upload>
          </a-form-model-item>
        </a-card>
        <!-- 船检证书 -->
        <a-card class="busenPic">
          <div class="card-title">船检证书</div>
          <a-form-model-item prop="inspectionCertificatePics" :wrapperCol="{span:24}">
            <upload
              :uploadName="'inspectionCertificatePics'"
              :fatherList="[]"
              :length="10"
              @uploadFile="inspectionCertificatePics"
            ></upload>
          </a-form-model-item>
        </a-card>
        <!-- 配员证书 -->
        <a-card class="busenPic">
          <div class="card-title">配员证书</div>
          <a-form-model-item prop="staffingCertificatePics" :wrapperCol="{span:24}">
            <upload
              :uploadName="'staffingCertificatePics'"
              :fatherList="[]"
              :length="10"
              @uploadFile="staffingCertificatePics"
            ></upload>
          </a-form-model-item>
        </a-card>
        <!-- 国籍证书 -->
        <a-card class="busenPic">
          <div class="card-title">国籍证书</div>
          <a-form-model-item prop="nationalityCertificatePics" :wrapperCol="{span:24}">
            <upload
              :uploadName="'nationalityCertificatePics'"
              :fatherList="[]"
              :length="10"
              @uploadFile="nationalityCertificatePics"
            ></upload>
          </a-form-model-item>
        </a-card>
        <!-- 所有权证书 -->
        <a-card class="busenPic">
          <div class="card-title">所有权证书</div>
          <a-form-model-item prop="ownershipCertificatePics" :wrapperCol="{span:24}">
            <upload
              :uploadName="'ownershipCertificatePics'"
              :fatherList="[]"
              :length="10"
              @uploadFile="ownershipCertificatePics"
            ></upload>
          </a-form-model-item>
        </a-card>
      </a-form-model>
    </div>
    <div class="creat_button">
      <a-button
        type="primary"
        :loading="createStatus"
        @click="save"
        style="float:right;margin-top:12px"
      >保存</a-button>
    </div>

    <agreement-modal
      :visible="agreementVisible"
      @set-agreement-visible="setAgreementVisible"
      @handle-agreement="handleAgreement"
    />
    <agreement-view-modal
      :visible="agreementViewVisible"
      :agreement="custInfoContract"
      @set-agview-visible="setAgreementViewVisible"
    />
  </div>
</template>
<script>
import agreementModal from '@/page/landCenter/agreementUploadModal'
import agreementViewModal from '@/page/landCenter/agreementViewModal'
import upload from '@/components/UpLoad'
import _ from 'lodash/debounce'
import { addShipInfo, getShipOwnerByNameLike } from '@/api/shipCenter'

const fomrMessage = `必填项不能为空`

export default {
  data () {
    // lodash-debounce
    this.onSearch = _(this.onSearch, 800)
    // 验证船APP账号
    let valiatePhone = (rule, value, callback) => {
      if (!this.form.shipInfoAccount.phone) {
        callback(new Error(fomrMessage))
      } else {
        callback()
      }
    }
    // 验证船长姓名
    let valiateName = (rule, value, callback) => {
      if (!this.form.shipInfoAccount.captainName) {
        callback(new Error(fomrMessage))
      } else {
        callback()
      }
    }

    let validateContractPics = (rule, value, callback) => {
      if (this.form.shipInfoContractList.length === 0) {
        callback(new Error(fomrMessage))
      } else {
        callback()
      }
    }

    return {
      basePath: '/shipCenter',
      routes: [
        {
          path: '/shipManagement',
          breadcrumbName: '船舶管理'
        },
        {
          path: '',
          breadcrumbName: '创建船舶'
        }
      ],
      labelCol: { span: 7 },
      wrapperCol: { span: 17 },
      limitNumber: 20,
      form: {
        custId: '',
        name: '', // 船舶名称
        identifier: '', // 船舶识别号
        imo: '', // IMO编号
        loadingCapacity: '', // 装载量（TEU）
        shipType: '', // 船舶类型
        buildTime: '', // 建成日期
        portOfRegistry: '', // 船籍港
        length: '', // 船长
        width: '', // 船宽
        height: '', // 船高
        depth: '', // 型深
        tonnage: '', // 总吨位，非必传
        netTonnage: '', // 净吨位，非必传
        inspectionTime: '', // 下次年检日期
        maintenanceTime: '', // 下次保养日期
        insuranceExpireTime: '', // 保险到期日期
        isSelfOperation: '', // 经营类型
        status: '', // 状态 1正常，0冻结
        alarmOilQuantity: '', // 告警油量
        shipInfoContractList: [], // 船舶合同
        operationCertificatePics: '', // 船舶运营证
        insurancePolicyPics: '', // 保险保单
        inspectionCertificatePics: '', // 船检证书
        staffingCertificatePics: '', // 配员证书
        nationalityCertificatePics: '', // 国籍证书
        ownershipCertificatePics: '', // 所有权证书
        shipInfoAccount: {
          phone: '', // 船App账号
          password: 'ec8883ad36104864fca7b6d1e16b6447', // 密码
          captainName: '' // 船长姓名
        }
      },
      rules: {
        // custId: [{ required: true, message: fomrMessage, trigger: ['blur', 'change'] }],
        name: [{ required: true, message: fomrMessage, trigger: 'blur' }],
        identifier: [{ required: true, message: fomrMessage, trigger: 'blur' }],
        imo: [{ required: true, message: fomrMessage, trigger: 'blur' }],
        loadingCapacity: [
          { required: true, message: fomrMessage, trigger: 'blur' }
        ],
        shipType: [{ required: true, message: fomrMessage, trigger: 'blur' }],
        buildTime: [
          { required: true, message: fomrMessage, trigger: 'change' }
        ],
        portOfRegistry: [
          { required: true, message: fomrMessage, trigger: 'blur' }
        ],
        length: [{ required: true, message: fomrMessage, trigger: 'blur' }],
        width: [{ required: true, message: fomrMessage, trigger: 'blur' }],
        height: [{ required: true, message: fomrMessage, trigger: 'blur' }],
        depth: [{ required: true, message: fomrMessage, trigger: 'blur' }],
        inspectionTime: [
          { required: true, message: fomrMessage, trigger: 'change' }
        ],
        maintenanceTime: [
          { required: true, message: fomrMessage, trigger: 'change' }
        ],
        insuranceExpireTime: [
          { required: true, message: fomrMessage, trigger: 'change' }
        ],
        isSelfOperation: [
          { required: true, message: fomrMessage, trigger: 'blur' }
        ],
        status: [{ required: true, message: fomrMessage, trigger: 'blur' }],
        alarmOilQuantity: [
          { required: true, message: fomrMessage, trigger: 'blur' }
        ],
        phone: [{ required: true, validator: valiatePhone, trigger: 'blur' }],
        captainName: [
          { required: true, validator: valiateName, trigger: 'blur' }
        ],
        contractPics: [
          { required: true, validator: validateContractPics, trigger: 'change' }
        ],
        operationCertificatePics: [
          { required: true, message: fomrMessage, trigger: 'change' }
        ],
        handleShipContract: [
          { required: true, message: fomrMessage, trigger: 'change' }
        ],
        insurancePolicyPics: [
          { required: true, message: fomrMessage, trigger: 'change' }
        ],
        inspectionCertificatePics: [
          { required: true, message: fomrMessage, trigger: 'change' }
        ],
        staffingCertificatePics: [
          { required: true, message: fomrMessage, trigger: 'change' }
        ],
        nationalityCertificatePics: [
          { required: true, message: fomrMessage, trigger: 'change' }
        ],
        ownershipCertificatePics: [
          { required: true, message: fomrMessage, trigger: 'change' }
        ]
      },
      shipOwner: [],
      selectObj: {},
      btnControl: {},
      // 合同
      custInfoContract: {
        name: '', // 合同名称
        beginTime: '', // 合同有效期
        endTime: '', // 合同有效期
        pictures: '' // 上传合同
      },
      agreementVisible: false,
      agreementViewVisible: false,
      createStatus: false
    }
  },
  methods: {
    getColor (beginTime, endTime) {
      const isOver = new Date(`${endTime} 23:59:59`).getTime() < new Date().getTime() || new Date(`${beginTime}`).getTime() > new Date().getTime()
      return isOver ? 'grey' : '#1890ff'
    },
    uploadAgreement () {
      this.agreementVisible = true
    },
    setAgreementVisible (visible) {
      this.agreementVisible = visible
    },
    handleAgreement (agreement) {
      this.form.shipInfoContractList.push({...agreement})
      this.agreementVisible = false
    },
    checkAgreement (index) {
      this.agreementViewVisible = true
      this.custInfoContract = Object.assign({}, this.form.shipInfoContractList[index])
    },
    setAgreementViewVisible (visible) {
      this.agreementViewVisible = visible
    },
    // 模糊搜索
    getShipOwner (e) {
      let _this = this
      getShipOwnerByNameLike(e)
        .then(res => {
          _this.shipOwner = res.data
        })
        .catch(rs => {})
    },
    // 船舶新增
    plusShip (e) {
      this.createStatus = true
      addShipInfo(e)
        .then(res => {
          if (res.code === 0) {
            this.$message.success('创建成功！')
            setTimeout(() => {
              this.createStatus = false
              this.$router.push({ path: '/shipCenter/shipManagement' })
            }, 1500)
          }
        })
        .catch(rs => {
          this.createStatus = false
        })
    },
    dateChange0 (date, dateString) {
      this.form.buildTime = dateString
    },
    dateChange1 (date, dateString) {
      this.form.inspectionTime = dateString
    },
    dateChange2 (date, dateString) {
      this.form.maintenanceTime = dateString
    },
    dateChange3 (date, dateString) {
      this.form.insuranceExpireTime = dateString
    },
    save () {
      if (!this.btnControl.create) {
        this.$message.error('您无此权限！')
        return false
      }
      // if (!this.createStatus) {
      //   this.$message.error('请勿重复提交！')
      //   return false
      // }
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          // alert('submit!')
          // // console.log(this.form)
          let param = this.form
          if (this.form.isSelfOperation === 1) {
            delete param.custId
          } else {
            if (!this.form.custId) {
              this.$message.error('租赁类型船舶，船东信息为必填项！')
              return false
            }
          }
          this.plusShip(param)
        }
      })
    },
    onSearch (searchText) {
      // // console.log(searchText)
      this.getShipOwner({
        status: 1,
        nameLike: searchText,
        belongCompany: 'JIA_CHUANG',
        custTypeLike: 'SUPPLIER',
        isPayable: 1
      })
    },
    onSelect (val, option) {
      this.form.custId = this.shipOwner[option.key].id
      this.selectObj = this.shipOwner[option.key]
    },
    operationCertificatePics (e) {
      this.form.operationCertificatePics = e
    },
    handleShipContract (e) {
      this.form.handleShipContract = e
    },
    insurancePolicyPics (e) {
      this.form.insurancePolicyPics = e
    },
    inspectionCertificatePics (e) {
      this.form.inspectionCertificatePics = e
    },
    staffingCertificatePics (e) {
      this.form.staffingCertificatePics = e
    },
    nationalityCertificatePics (e) {
      this.form.nationalityCertificatePics = e
    },
    ownershipCertificatePics (e) {
      this.form.ownershipCertificatePics = e
    }
  },
  components: {
    upload,
    [agreementModal.name]: agreementModal,
    [agreementViewModal.name]: agreementViewModal
  },
  mounted () {
    this.getShipOwner({
      status: 1,
      nameLike: '',
      belongCompany: 'JIA_CHUANG',
      custTypeLike: 'SUPPLIER',
      isPayable: 1
    })
    this.$nextTick(() => {
      this.btnControl = this.$root._bc
      // console.log(this.$root._bc)
    })
  }
}
</script>
<style lang="less" scoped>
#content {
  margin: 20px;
  .ant-card {
    position: relative;
    margin-bottom: 20px;
    border: none;
    .cardEdit {
      position: absolute;
      right: 24px;
      top: 24px;
      z-index: 2;
    }
    .card-title {
      position: relative;
      padding-left: 16px;
      font-size: 18px;
      line-height: 1;
      color: #000;
      margin-bottom: 20px;
      &:before {
        content: '';
        width: 5px;
        height: 18px;
        background: #1890ff;
        border-radius: 4px;
        position: absolute;
        left: 0;
        top: -1px;
      }
    }
    span {
      display: inline-block;
      height: 40px;
      line-height: 40px;
    }
  }
}
.ant-col-12 {
  padding-right: 50px;
}
</style>
